package com.face.server.config;

import com.face.server.entity.Admin;
import com.face.server.entity.Function;
import com.face.server.repository.AdminRepository;
import com.face.server.repository.AuthRepository;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private AuthRepository authRepository;

    @Autowired
    private AdminRepository adminRepository;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        String password = String.valueOf(token.getPassword());
        Admin admin=adminRepository.findByUsernameAndPassword(name,password);
        if (null == admin) {
            throw new AccountException("帐号或密码不正确！");
        }
        return new SimpleAuthenticationInfo(admin, password, getName());
    }

    /**

     * 授权

     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        System.out.println("权限认证方法：MyShiroRealm.doGetAuthorizationInfo()");
        Admin user = (Admin) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        info.setRoles(new HashSet<String>(user.getRole().getFunctions().stream().map(e->e.getFName()).collect(Collectors.toList())));
        return info;
    }
}